<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>商品详情</title>
  <link rel="stylesheet" href="./css/detail.css">
  <script src="./js/cookie.js"></script>
  <script src="./js/requset.js"></script>
</head>

<body>
  <div class="w">

  </div>
</body>
<script>
  // 获取当前商品的id - 从地址栏中获取商品id
  var reg = /id=([^&]+)/
  var arr = location.search.match(reg)
  if (arr && arr[1]) {
    var id = arr[1]
  }
  const w = document.querySelector('.w')
  request({
    url: `/goods/api/detail/${id}`
  }).then((res) => {
    let data = res.data.docs
    console.log(data);
    let html = `
      <img src="${data.img_small_logo}" alt="">
      <div class="rigth">
        <p>${data.title}</p>
        <p>￥ ${data.price}</p>
        <a href="/list.html"><span>购物车列表</span> </a>
        
        <span>加入购物车</span>
      </div>
      <div>
      `
    w.innerHTML = html
    cart()
  })
  //购物车逻辑
  function cart() {
    document.querySelectorAll('span')[1].onclick = function () {
      // 判断用户是否登录
      var username = getCookie('username')
      if (!username) {
        alert('请先登录')
        // 将当前地址存起来
        localStorage.setItem('url', location.href)
        location.href = '/login.html'
        return false
      }
      // 登录成功
      // 添加购物车，本质就是将当前商品数据存储下来，到购物车页面的时候获取出来展示
      request({
        url: '/cart/api/add',
        method: 'post',
        headers: {
          Authorization: localStorage.getItem('token')
        },
        data: {
          goodsid: id,
          goodsnumber: 1,
          userid: getCookie('userid')
        }
      }).then(res => {
        // console.log(res);
        var { error_code, msg } = res
        alert(msg)
      })
    }
  }
</script>

</html>